import {Component, OnInit} from '@angular/core';
import {FormControl, FormGroup, Validators} from "@angular/forms";
import {BarnProduct} from "../../product/entity/barn-product";
import {ProductService} from "../../product/service/product.service";
import {Constants, StringTool} from "../../../../../tools";
import {ProjectProductService} from "../../service/project-product.service";
import {BarnProject} from "../../project/entity/barn-project";
import {environment} from "../../../../../../environments/environment";


@Component({
  selector: 'app-export-sql',
  templateUrl: './export-sql.component.html',
  styleUrls: ['./export-sql.component.less']
})
export class ExportSqlComponent implements OnInit {
  private readonly servicePrefix = environment.service.servicePrefix

  private readonly export_prefix = environment.serverName.document

  validateForm = new FormGroup({
    productId: new FormControl("", Validators.required),
    required: new FormControl(false),
    projectId: new FormControl('')
  })

  // end 不能小于 start
  start: number
  end: number

  allProducts: BarnProduct[] = []
  projects: BarnProject[] = []

  constructor(private productService: ProductService, private ppService: ProjectProductService) {
  }

  ngOnInit(): void {
    const param = new BarnProduct();
    param.enable = Constants.Enable.YES
    this.productService.query(param).subscribe(value => {
      this.allProducts = value.data
    })
  }

  requiredChange(include: boolean) {
    console.log(include)
    if (include) {
      const productId = this.validateForm.get("productId").value
      this.productChange(productId)
      this.validateForm.get("projectId").setValidators(Validators.required)
    } else {
      this.projects = []
      this.validateForm.get("projectId").clearValidators()
      this.validateForm.get("projectId").setValue('')
    }
    this.validateForm.get('projectId')!.markAsPristine();
    this.validateForm.get('projectId')!.updateValueAndValidity();
  }

  productChange(e) {
    this.projects = [];
    if (e) {
      this.ppService.getProjectByProduct(e).subscribe(value => this.projects = value);
    }
  }

  exportUrl() {
    let url = StringTool.concatUrl(this.servicePrefix, this.export_prefix, "sqlExport") +
      "?productId=" + this.validateForm.get("productId").value +
      "&projectId=" + this.validateForm.get("projectId").value

    if (typeof this.start === "number") {
      url = url + "&start=" + this.start
    }
    if (typeof this.end === 'number') {
      url = url + "&end=" + this.end
    }

    return url;
  }

  startMax() {
    if (typeof this.end === 'number') {
      return this.end - 1
    } else {
      return Number.MAX_VALUE
    }
  }

  endMin() {

    if (typeof this.start === 'number') {
      return this.start + 1
    } else {
      return 1
    }
  }
}
